package myapp.com.phoneguard.fragment;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import myapp.com.phoneguard.R;
import myapp.com.phoneguard.adapter.ContactsAdapter1;
import myapp.com.phoneguard.dao.DbManager;
import myapp.com.phoneguard.pojo.ContactModel;
import myapp.com.phoneguard.pojo.Info;
import myapp.com.phoneguard.view.PinnedHeaderDecoration;
import myapp.com.phoneguard.view.SearchEditText;
import myapp.com.phoneguard.view.Trans2PinYinUtil;
import myapp.com.phoneguard.view.WaveSideBar;

/**
 * 拨号界面
 */

public class CallFragment extends Fragment{
    private RecyclerView mContact;
    private WaveSideBar mWaveSideBar;
    private SearchEditText mSearchEditText;
    private List<ContactModel> mContactModels;
    private List<ContactModel> mShowModels;
    private ContactsAdapter1 mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //从数据库中得到拦截短信的集合
        super.onActivityCreated(savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_call, container, false);

        mContact = view.findViewById(R.id.main_recycler);
        mWaveSideBar = view.findViewById(R.id.side_bar);
        mSearchEditText = view.findViewById(R.id.main_search);

        mContactModels = new ArrayList<>();
        mContactModels.addAll(getInfos());

        mShowModels = new ArrayList<>();
        mShowModels.addAll(mContactModels);

        mAdapter = new ContactsAdapter1(mShowModels, new ContactsAdapter1.OnClickListener() {
            @Override
            public void onClickContact(String phone) {
                Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
                startActivity(intent);
            }
        });

        mContact.setLayoutManager(new LinearLayoutManager(getActivity()));
        final PinnedHeaderDecoration decoration = new PinnedHeaderDecoration();
        decoration.registerTypePinnedHeader(1, new PinnedHeaderDecoration.PinnedHeaderCreator() {
            @Override
            public boolean create(RecyclerView parent, int adapterPosition) {
                return true;
            }
        });
        mContact.addItemDecoration(decoration);
        mContact.setAdapter(mAdapter);

        // 侧边设置相关
        mWaveSideBar.setOnSelectIndexItemListener(new WaveSideBar.OnSelectIndexItemListener() {
            @Override
            public void onSelectIndexItem(String letter) {
                for (int i=0; i<mContactModels.size(); i++) {
                    if (mContactModels.get(i).getIndex().equals(letter)) {
                        ((LinearLayoutManager) mContact.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });


        // 搜索按钮相关
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mShowModels.clear();
                for (ContactModel model : mContactModels) {
                    String str = Trans2PinYinUtil.trans2PinYin(model.getName());
                    if (str.contains(s.toString()) || model.getName().contains(s.toString())) {
                        mShowModels.add(model);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        });

        return view;
    }

    //使用contentprovider获取通讯录中的所有联系人的姓名和电话
    private List<ContactModel> getInfos() {
        ContentResolver cr = getContext().getContentResolver();
        //得到的是所有的联系人信息
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null,
                null,
                null,
                null);
        List<ContactModel> infoList = new ArrayList<>();
        while (cursor.moveToNext()) {
            //Info info = new Info();
            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            String name = cursor.getString(nameFieldColumnIndex);

            // 取得联系人ID
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            //这里的URI是一个字段
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                    + contactId, null, null);

            //List<String> list = new ArrayList<>();
            // 取得电话号码(可能存在多个号码),这里我就默认一个人
            while (phone.moveToNext()) {
                String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                //这里把同一人不同电话分为不同行处理了
                ContactModel info = new ContactModel(name,strPhoneNumber);
                info.setName(name);
                info.setPhonenumber(strPhoneNumber);
                //判断这个info是否在黑名单中，如果在就不加入进去
                if (!DbManager.getInstance().phonenumberisExist(strPhoneNumber))
                    infoList.add(info);
            }
            phone.close();
        }
        cursor.close();
        return infoList;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mContactModels != null){
            mContactModels.clear();
            mContactModels = null;
        }
    }

}
